//
//  LoginViewController.m
//  AmazingShopping
//
//  Created by Tan on 4/18/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginCell.h"
#import "HomeViewController.h"
#import "RegisterViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
    self.navigationItem.title = @"Sign in";
    
    //Add touch event to table view
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [tableView addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;
    
    [self readUserData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    tableView = nil;
    emailTextField = nil;
    passwordTextField = nil;
    signInButton = nil;
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated{
    if (!isLogin) {
        [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];        
        [self isTextFilled];
    }    
}

- (void)readUserData{
    NSString *userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath: userInfoPath]){
    }else{
        userData = [[NSMutableDictionary alloc] initWithContentsOfFile: userInfoPath];
    }
}

- (void)hideKeyboard {
    [emailTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
}

- (IBAction)signInButtonClicked:(id)sender {
    //Set effect
    self.view.userInteractionEnabled = NO;
    self.view.alpha = 0.5;
    UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:loading];
    [loading startAnimating];
    
    if (isLogin) {
        NSString *userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath: userInfoPath]){
        }else{
            userData = [[NSMutableDictionary alloc] initWithContentsOfFile: userInfoPath];
            [userData setObject:@"NO" forKey:@"IsLogin"];
            [[userData objectForKey:@"ProductInCart"] removeAllObjects];
            [userData writeToFile:userInfoPath atomically:YES];
            NSString *path = [NSString stringWithFormat:@"%@/sign_out", serverPath];
            NSURL *url = [NSURL URLWithString:path];
            ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:url];
            [request addPostValue:[userData valueForKey:@"ID"] forKey:@"id"];
            [request setDelegate:self];
            [request startSynchronous];
            
            //Stop effect
            [loading stopAnimating];
            self.view.userInteractionEnabled = YES;
            self.view.alpha = 1;
            
            NSError *error = [request error];
            if (error) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Something is wrong. Try again later" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                [alertView show];
            }else{
                isLogin = NO;
                [self.navigationController popToRootViewControllerAnimated:YES];
            }            
        }
    }else{
        [passwordTextField resignFirstResponder];
        NSString *path = [NSString stringWithFormat:@"%@/sign_in", serverPath];
        NSURL *url = [NSURL URLWithString:path];
        ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:url];
        [request addPostValue:emailTextField.text forKey:@"email"];
        [request addPostValue:passwordTextField.text forKey:@"password"];
        [request setDelegate:self];
        [request startSynchronous];
        
        //Stop effect
        [loading stopAnimating];
        self.view.userInteractionEnabled = YES;
        self.view.alpha = 1;
        
        NSError *error = [request error];
        if (!error) {
            NSData *responseData = [request responseData];
            JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
            NSArray *userInfo = [jsonDecoder objectWithData:responseData];
            if (userInfo != NULL) {
                NSString *userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if (![fileManager fileExistsAtPath: userInfoPath]){
                }else{                    
                    [userData setObject:@"YES" forKey:@"IsLogin"];
                    [userData setObject:[[userInfo objectAtIndex:0] valueForKey:@"customer_email"] forKey:@"Email"];
                    [userData setObject:[[userInfo objectAtIndex:0] valueForKey:@"customer_name"] forKey:@"Name"];
                    [userData setObject:[[userInfo objectAtIndex:0] valueForKey:@"customer_id"] forKey:@"ID"];
                    [userData writeToFile:userInfoPath atomically:YES];
                    isLogin = YES;
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
            }else{
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Sorry, the e-mail address or password you entered is incorrect." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                [alertView show];
            }
        }else{
            NSLog(@"Something's wrong with sign in function");
        }
    }
    
    //Post notification about user status
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangedUserStatus" object:self];
}

- (BOOL)isTextFilled{
    if ((emailTextField.text == nil) || ([emailTextField.text isEqualToString:@""]) || ([passwordTextField.text isEqualToString:@""]) || (passwordTextField.text == nil)) {
        signInButton.enabled = NO;
        return NO;
    }
    signInButton.enabled = YES;
    return YES;
}

#pragma Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (isLogin) {
        return 1;
    }else{
        return 3;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (isLogin) {
        return 1;
    }else{
        if (section == 0) {
            return 2;
        }else if (section == 1){
            return 3;
        }else{
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = [indexPath section];
    if (section == 1) {
        if ([indexPath row] == 2) {
            return 60.0f;
        }
        return 30.0f;
    }else{
        return 44.0f;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (isLogin) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SignOutCell"];
        CGRect frame = cell.frame;
        frame = signInButton.frame;
        frame.origin.x = cell.frame.origin.x+10;
        frame.origin.y = cell.frame.origin.y+10;
        signInButton.frame = frame;
        [signInButton setTitle:@"Sign Out" forState:UIControlStateNormal];
        [cell addSubview:signInButton];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundView = [[UIView alloc]initWithFrame:CGRectZero];
        return cell;
    }else{
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SignInCell"];
        NSInteger section = [indexPath section];
        NSInteger row = [indexPath row];
        if (section == 0) {
            if (row == 0) {
                CGRect frame = cell.frame;
                emailTextField = [[UITextField alloc]initWithFrame:CGRectMake(frame.origin.x+15, frame.origin.y, frame.size.width-25, frame.size.height)];
                emailTextField.placeholder = @"E-mail address";
                emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                emailTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                emailTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                emailTextField.delegate = self;
                [emailTextField addTarget:self action:@selector(isTextFilled) forControlEvents:UIControlEventEditingChanged];
                [emailTextField setKeyboardType:UIKeyboardTypeEmailAddress];
                [cell addSubview:emailTextField];
            }else if (row == 1){
                CGRect frame = cell.frame;
                passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(frame.origin.x+15, frame.origin.y, frame.size.width-25, frame.size.height)];
                passwordTextField.placeholder = @"Password";
                passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                passwordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                passwordTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                passwordTextField.secureTextEntry = YES;
                passwordTextField.delegate = self;
                [passwordTextField addTarget:self action:@selector(isTextFilled) forControlEvents:UIControlEventEditingChanged];
                [cell addSubview:passwordTextField];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }else if (section == 1){
            CGRect frame = cell.frame;
            if (row == 0) {
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x+10, frame.origin.y, frame.size.width-20, frame.size.height)];
                label.backgroundColor = [UIColor clearColor];
                label.text = @"By signing in you agree to Our Conditions of Use and Privacy Policy";
                label.font = [UIFont fontWithName:@"Helvetica" size:12.0f];
                label.numberOfLines = 0;
                label.textColor = [UIColor colorWithRed:50/255.0 green:79/255.0 blue:123/255.0 alpha:1];
                [label sizeToFit];
                
                label.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(legalLabelClicked:)];
                [label addGestureRecognizer:tapGesture];
                [cell addSubview:label];
            }else if (row == 1){
                frame = signInButton.frame;
                frame.origin.x = cell.frame.origin.x+10;
                frame.origin.y = cell.frame.origin.y+10;
                signInButton.frame = frame;
                [cell addSubview:signInButton];
            }else{
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x+10, frame.origin.y+20, frame.size.width-20, frame.size.height)];
                label.backgroundColor = [UIColor clearColor];
                label.text = @"Forgot your password?";
                label.font = [UIFont fontWithName:@"Helvetica" size:13.0f];
                label.textColor = [UIColor colorWithRed:50/255.0 green:79/255.0 blue:123/255.0 alpha:1];
                label.numberOfLines = 0;
                [label sizeToFit];
                
                label.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(forgotPasswordLabelClicked:)];
                [label addGestureRecognizer:tapGesture];
                [cell addSubview:label];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundView = [[UIView alloc]initWithFrame:CGRectZero];
        }else if (section == 2){
            cell.textLabel.text = @"Create account";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }    
        
        return cell;
    }    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (isLogin) {
        return [NSString stringWithFormat:@"You are signed in: %@", [userData valueForKey:@"Name"]];
    }else{
        if (section == 2) {
            return @"Don't have account ?";
        }else{
            return nil;
        }
    }    
}

#pragma mark Table View Delegates

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([indexPath section] == 2) {
        RegisterViewController *nextController = [[RegisterViewController alloc]init];
        [self.navigationController pushViewController:nextController animated:YES];
    }
}

#pragma mark Text Field Delegates
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == emailTextField) {
        [passwordTextField becomeFirstResponder];
        return NO;
    }else if (![emailTextField.text isEqualToString:@""]){
        [self signInButtonClicked:nil];
    }
    return YES;
}

- (void)legalLabelClicked:(UITapGestureRecognizer *)sender{
    UILabel *label = (UILabel *)sender.view;
    NSLog(@"%@", label.text);
}

- (void)forgotPasswordLabelClicked:(UITapGestureRecognizer *)sender{
    NSLog(@"forgot");
}

@end
